package cn.tedu.ivos.base.security;

import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 没有授权异常的处理器
 */
@Service
@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     *
     * @param request
     * @param response
     * @param authException  没有授权引起的异常
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.debug("未授权访问");
        //设置响应的状态码为401，表示未授权访问
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        //设置响应内容类型和编码集
        response.setContentType("application/json;charset=UTF-8");
        //响应内容
        PrintWriter writer = response.getWriter();
        //准备一个用于响应内容的JSON对象
        JsonResult jsonResult = new JsonResult(StatusCode.NOT_LOGIN);
        writer.write(JSON.toJSONString(jsonResult));
        //刷新并关闭
        writer.flush();
        writer.close();
    }
}
